package com.hj.jwtserver.config;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @Author : hujing
 * @Date: 2025/6/19 14:51
 * @Description: 创建一个JWT工具类
 */
@Component
public class JwtTokenProvider {
    
    @Value("${jwt.secret}")
    private String jwtSecret;
    @Value("${jwt.expiration}")
    private int jwtExpirationInMs;
    
    public String generateToken(String username){
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes());
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date()) // 颁发时间
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs)) // 过期时间
                .signWith(key, SignatureAlgorithm.HS256)
                .compact(); // 压缩jwt
    }
    
    public String getUsernameFromToken(String token){
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes());
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                // 这里注意下,如果有签名,就使用parseClaimsJws()方法,否则使用parseClaimsJwt()方法
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
}
